package com.yc4.datesource;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Deque;
import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.logging.Logger;

/**
 * @ClassName MyDataSource
 * @since: 2023/7/26 11:39
 * @auth: kirito
 * @description:
 **/
@Component
public class MyDataSource implements DataSource {
    private ConcurrentLinkedDeque<MyConnection> pool;
    //配置后注入  结合属性文件完成注入操作
    @Value("${coreSize}")
    private int coreSize;
    @Value("${user}")
    private String user;
    @Value("${password}")
    private String password;
    @Value("${url}")
    private String url;

    private MyDataSource() {
        System.out.println("MyDataSource构造方法");
    }

    @PostConstruct  //此方法  在构造方法执行后执行 =》 初始化连接池
    public void init() throws SQLException {
        System.out.println("init");
        pool = new ConcurrentLinkedDeque<>();
        for (int i = 0; i < coreSize; i++) {
            MyConnection mc = new MyConnection();
            mc.statue = false;
            mc.con = DriverManager.getConnection(url, user, password);
            pool.add(mc);
        }
    }
    class MyConnection {
        Connection con;
        boolean statue; //true 在用 false 空闲
    }

    public void returnConnection(Connection connection) {
        MyConnection mc = new MyConnection();
        mc.statue = false;
        mc.con = connection;
        this.pool.add(mc);
    }
    @Override
    public Connection getConnection() throws SQLException {
        do {
            MyConnection mc = this.pool.poll();
            if (mc == null) {
                return null;
            }
            if (!mc.statue) {
                return mc.con;
            }
        } while (true);
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return null;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }


}
